package org.example.command;

import org.example.model.HTMLDocument;
import org.jsoup.nodes.Element;

public class EditElementIdCommand implements CanUndoCommand {

    private final Element element;
    private final String newId;
    private String oldId;

    private EditElementIdCommand(HTMLDocument document, String oldId, String newId) {
        this.element = document.getDocument().getElementById(oldId);
        this.newId = newId;
    }

    public static Command create(HTMLDocument document, String oldId, String newId) {
        return new EditElementIdCommand(document, oldId, newId);
    }

    @Override
    public boolean execute() {

        try {
            oldId = element.id();
            element.attr("id", newId);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public void undo() {
        element.attr("id", oldId);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        EditElementIdCommand other = (EditElementIdCommand) obj;
        return element.equals(other.element) && newId.equals(other.newId);
    }

    @Override
    public int hashCode() {
        return 31 * element.hashCode() + newId.hashCode();
    }

    @Override
    public String toString() {
        return "EditElementIdCommand{" + "element=" + element + ", newId='" + newId + "'}";
    }
}
